package com.cl.base.auth.service.impl;

import com.cl.base.auth.entity.AuthUser;
import com.cl.base.constant.CommonConstants;

import com.cl.base.entity.SysRoleMenu;
import com.cl.base.entity.SysUser;
import com.cl.base.entity.SysUserRole;
import com.cl.base.service.SysMenuService;
import com.cl.base.service.SysRoleMenuService;
import com.cl.base.service.SysUserRoleService;
import com.cl.base.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;
    private final SysRoleMenuService sysRoleMenuService;
    private final SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findOneByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        Long userId = sysUser.getUserId();
        List<SysUserRole> userRoles = sysUserRoleService.findByUserId(userId);
        List<Long> roles = userRoles.stream().map(SysUserRole::getRoleId).toList();
        List<SysRoleMenu> roleMenus = sysRoleMenuService.findByRoleIds(roles);
        Set<Long> menus = roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
        List<String> permissions = sysMenuService.findPermissionByMenuIds(menus);
        return new AuthUser(userId,
                sysUser.getDeptId(),
                sysUser.getUsername(),
                sysUser.getPassword(),
                true,
                true,
                true,
                !sysUser.getLockFlag().equals(CommonConstants.STATUS_LOCK),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]))
        );
    }
}
